﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;
using YunHao;

namespace UnknowWorld.CardGame
{

    public class CardPool : MonoBehaviour
    {

        public static CardPool Instance
        {
            get
            {
                if (!instance)
                    instance = new GameObject("CardPool", typeof(CardPool)).GetComponent<CardPool>();
                return instance;
            }
        }

        private static CardPool instance;

        void Awake()
        { 
            if(!instance)
                instance = this;
        }

        private void OnEnable()
        {
            InitCardPool();
        }

        private void OnDisable()
        {
            _dataPool.Clear();
            DestroyPicturePool();
            _dataLoaded = false;
        }

        #region Load Data
        /// <summary>
        /// 所有卡牌
        /// </summary>
        public List<Card> Cards
        {
            get
            {
                return _dataPool;
            }
        }
        /// <summary>
        /// 是否加载成功
        /// </summary>
        public bool Loaded
        {
            get
            {
                return _dataLoaded;
            }
        }

        /// <summary>
        /// 卡牌池
        /// </summary>
        private List<Card> _dataPool = new List<Card>();

        /// <summary>
        /// 卡牌图片路径
        /// </summary>
        private string _cardPictureDir;

        /// <summary>
        /// 卡牌数据加载是否完成
        /// </summary>
        private bool _dataLoaded;

        /// <summary>
        /// 初始化本地卡牌
        /// </summary>
        void InitCardPool()
        {
            string cardDir = Path.Combine(Application.streamingAssetsPath, "Card");
            string cardDataPath = Path.Combine(cardDir, "Cards.dat");
            _cardPictureDir = Path.Combine(cardDir, "Images");
            LoadCardPool(cardDataPath);
        }

        /// <summary>
        /// 加载本地卡牌池
        /// </summary>
        /// <param name="path">卡牌数据文件路径</param>
        void LoadCardPool(string path)
        {
            XmlControl.ReadXmlAsync<List<Card>>(path, (cards) =>
            {
                _dataPool = cards;
                _dataLoaded = true;
            }, (err) =>
            {
                Debug.LogErrorFormat("Card Load Fail:", err);
            });
        }

        /// <summary>
        /// 通过key获取Card
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Card CardByKey(string key)
        {
            Card card = null;
            foreach (var cd in _dataPool)
            {
                if (cd.Key == key)
                {
                    card = cd.Clone();
                    break;
                }
            }
            return card;
        }

        #endregion

        #region Card Picture Pool
        /// <summary>
        /// 卡牌图片池
        /// </summary>
        private Dictionary<string, Texture2D> _cardPicturePool = new Dictionary<string, Texture2D>();

        /// <summary>
        /// 销毁图片池
        /// </summary>
        void DestroyPicturePool()
        {
            foreach (var kv in _cardPicturePool)
            {
                var texture = kv.Value;
                if (texture) Destroy(texture);
            }
            _cardPicturePool.Clear();
        }

        /// <summary>
        /// 获取卡牌图片Sprite
        /// </summary>
        /// <param name="card"></param>
        /// <returns></returns>
        public void LoadCardPictureSprite(Card card,System.Action<Sprite> onFinish)
        {
            System.Action<Texture2D> onSuccess = (tex)=>
            {
                var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(.5f, .5f));
                onFinish(sprite);
            };

            if (_cardPicturePool.ContainsKey(card.PicAddress))
            {
                onSuccess(_cardPicturePool[card.PicAddress]);
                return;
            }
            string url = Path.Combine(_cardPictureDir, card.PicAddress);
            ResourceLoadControl.Instance.LoadTexture2D(url,(tex) =>
            {
                if (tex)
                {
                    if (_cardPicturePool.ContainsKey(card.PicAddress))
                    {
                        onSuccess(_cardPicturePool[card.PicAddress]);
                        Destroy(tex);
                    }
                    else
                    {
                        _cardPicturePool.Add(card.PicAddress,tex);
                        onSuccess(tex);
                    }
                }
                else
                {
                    Debug.LogWarning("无法获取卡牌图片");
                }
            },(err)=>
            {
                Debug.LogWarningFormat("获取卡牌图片失败:{0}",err);
            });
        }
        #endregion
    }
}